package com.data.modules.online.cgreport.service.impl;

import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.data.common.api.vo.Result;
import com.data.common.util.dynamic.db.DynamicDBUtil;
import com.data.modules.online.cgform.enums.DataBaseEnum;
import com.data.modules.online.cgform.util.CgformUtil;
import com.data.modules.online.cgform.util.OnlSlotRender;
import com.data.modules.online.cgreport.model.OnlCgreportModel;
import com.data.modules.online.config.datasourceConfig.OnlineFieldConfig;
import com.data.modules.online.config.executor.ConditionHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import com.data.common.exception.BootException;
import com.data.common.system.api.ISysBaseAPI;
import com.data.common.system.query.QueryGenerator;
import com.data.common.system.vo.DictModel;
import com.data.common.system.vo.DynamicDataSourceModel;
import com.data.common.util.dynamic.db.DataSourceCachePool;
import com.data.common.util.ConvertUtils;
import com.data.modules.online.cgreport.entity.OnlCgreportHead;
import com.data.modules.online.cgreport.entity.OnlCgreportItem;
import com.data.modules.online.cgreport.entity.OnlCgreportParam;
import com.data.modules.online.cgreport.mapper.OnlCgreportHeadMapper;
import com.data.modules.online.cgreport.common.CgReportConstant;
import com.data.modules.online.cgreport.service.IOnlCgreportHeadService;
import com.data.modules.online.cgreport.service.IOnlCgreportItemService;
import com.data.modules.online.cgreport.service.IOnlCgreportParamService;
import com.data.modules.online.cgreport.util.CgReportSqlFiledParseUtils;
import com.data.modules.online.cgreport.util.CgReportSqlUtil;
import com.data.modules.online.config.exception.DBException;
import com.data.modules.online.config.executor.DbTableUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@SuppressWarnings("ALL")
@Service("onlCgreportHeadServiceImpl")
public class OnlCgreportHeadServiceImpl extends ServiceImpl<OnlCgreportHeadMapper, OnlCgreportHead> implements IOnlCgreportHeadService {
    @Autowired
    private OnlCgreportHeadMapper mapper;
    @Autowired
    private IOnlCgreportItemService onlCgreportItemService;
    @Autowired
    private IOnlCgreportParamService onlCgreportParamService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    private static /* synthetic */ java.lang.Object m337a(java.lang.invoke.SerializedLambda r4) {
        /*
        // Method dump skipped, instructions count: 1012
        */
        throw new UnsupportedOperationException("Method not decompiled: com.data.modules.online.cgreport.service.p016a.OnlCgreportHeadServiceImpl.m337a(java.lang.invoke.SerializedLambda):java.lang.Object");
    }

    @Override
    public Map<String, Object> executeSelectSql(String sql, String onlCgreportHeadId, Map<String, Object> params) throws java.sql.SQLException {
        String dataType = null;

        try {
            dataType = DbTableUtil.getDatabaseType();
        } catch (DBException var23) {
            var23.printStackTrace();
        }

        LambdaQueryWrapper<OnlCgreportParam> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(OnlCgreportParam::getCgrheadId, onlCgreportHeadId);
        List var6 = this.onlCgreportParamService.list(queryWrapper);
        if (var6 != null && var6.size() > 0) {
            Iterator var7 = var6.iterator();

            while(var7.hasNext()) {
                OnlCgreportParam var8 = (OnlCgreportParam)var7.next();
                Object var9 = params.get("self_" + var8.getParamName());
                String var10 = "";
                if (var9 != null) {
                    var10 = var9.toString();
                } else if (var9 == null && ConvertUtils.isNotEmpty(var8.getParamValue())) {
                    var10 = var8.getParamValue();
                }

                String var11 = "${" + var8.getParamName() + "}";
                if (sql.indexOf(var11) > 0) {
                    if (var10 != null && var10.startsWith("'") && var10.endsWith("'")) {
                        var10 = var10.substring(1, var10.length() - 1);
                    }

                    sql = sql.replace(var11, var10);
                } else if (ConvertUtils.isNotEmpty(var10)) {
                    params.put("popup_param_pre__" + var8.getParamName(), var10);
                }
            }
        }

        HashMap var24 = new HashMap();
        Integer var25 = ConvertUtils.getInt(params.get("pageSize"), 10);
        Integer var26 = ConvertUtils.getInt(params.get("pageNo"), 1);
        Page var28 = new Page((long)var26, (long)var25);
        LambdaQueryWrapper<OnlCgreportItem> var27 = new LambdaQueryWrapper();
        var27.eq(OnlCgreportItem::getCgrheadId, onlCgreportHeadId);
        ArrayList var12 = new ArrayList();
        String[] var13 = (String[])params.keySet().toArray(new String[0]);
        int var14 = var13.length;

        String var17;
        for(int var15 = 0; var15 < var14; ++var15) {
            String var16 = var13[var15];
            if (var16.startsWith("force_")) {
                var17 = var16.substring("force_".length());
                var12.add(var17);
                params.put(var17, params.get(var16));
            }
        }

        List<OnlCgreportItem> var29;
        if (var12.size() > 0) {
            var27.in(OnlCgreportItem::getFieldName, var12);
            var29 = this.onlCgreportItemService.list(var27);
            var29.forEach((var0) -> {
                var0.setIsSearch(1);
            });
        } else {
            var27.eq(OnlCgreportItem::getIsSearch, 1);
            var29 = this.onlCgreportItemService.list(var27);
        }

        sql = QueryGenerator.convertSystemVariables(sql);
        ArrayList var30 = new ArrayList();
        Iterator var31 = var29.iterator();

        while(var31.hasNext()) {
            OnlCgreportItem var33 = (OnlCgreportItem)var31.next();
            var30.add(new OnlineFieldConfig(var33));
        }

        String tmpTable = "rp_temp.";
        ConditionHandler var34 = new ConditionHandler(tmpTable, dataType);
        var17 = var34.mo1320a(var30, params);
        Map var18 = var34.getSqlParams();
        if (ReUtil.contains(" order\\s+by ", sql.toLowerCase()) && "SQLSERVER".equalsIgnoreCase(dataType)) {
            throw new BootException("SqlServer不支持SQL内排序!");
        } else {
            String exeSQL = "select * from (" + sql + ") rp_temp ";
            if (var17.trim().length() > 0) {
                exeSQL = exeSQL + " where " + var17;
            }

            Object order = params.get("column");
            if (order != null) {
                exeSQL = exeSQL + " order by rp_temp." + order.toString() + " " + params.get("order").toString();
            }

            Object var21;
            if (Boolean.valueOf(String.valueOf(params.get("getAll")))) {
                List var22 = this.mapper.selectByCondition(exeSQL, var18);
                var21 = new Page();
                ((IPage)var21).setRecords(var22);
                ((IPage)var21).setTotal((long)var22.size());
            } else {
                var21 = this.mapper.selectPageByCondition(var28, exeSQL, var18);
            }

            var24.put("total", ((IPage)var21).getTotal());
            var24.put("records", CgformUtil.m280d(((IPage)var21).getRecords()));
            return var24;
        }
    }

    @Override
    public Map<String, Object> executeSelectSqlDynamic(String dbKey, String sql, Map<String, Object> params, String onlCgreportHeadId) {
        String var5 = (String)params.get("order");
        String var6 = (String)params.get("column");
        int var7 = ConvertUtils.getInt(params.get("pageNo"), 1);
        int var8 = ConvertUtils.getInt(params.get("pageSize"), 10);
        DynamicDataSourceModel var9 = DataSourceCachePool.getCacheDynamicDataSourceModel(dbKey);
        if (ReUtil.contains(" order\\s+by ", sql.toLowerCase()) && "3".equalsIgnoreCase(var9.getDbType())) {
            throw new BootException("SqlServer不支持SQL内排序!");
        } else {
            LambdaQueryWrapper<OnlCgreportParam> var10 = new LambdaQueryWrapper();
            var10.eq(OnlCgreportParam::getCgrheadId, onlCgreportHeadId);
            List var11 = this.onlCgreportParamService.list(var10);
            OnlCgreportParam var13;
            String var15;
            if (var11 != null && var11.size() > 0) {
                for(Iterator var12 = var11.iterator(); var12.hasNext(); sql = sql.replace("${" + var13.getParamName() + "}", var15)) {
                    var13 = (OnlCgreportParam)var12.next();
                    Object var14 = params.get("self_" + var13.getParamName());
                    var15 = "";
                    if (var14 != null) {
                        var15 = var14.toString();
                    } else if (var14 == null && ConvertUtils.isNotEmpty(var13.getParamValue())) {
                        var15 = var13.getParamValue();
                    }
                }
            }

            LambdaQueryWrapper<OnlCgreportItem> var26 = new LambdaQueryWrapper();
            var26.eq(OnlCgreportItem::getCgrheadId, onlCgreportHeadId);
            var26.eq(OnlCgreportItem::getIsSearch, 1);
            List var27 = this.onlCgreportItemService.list(var26);
            sql = QueryGenerator.convertSystemVariables(sql);
            ArrayList var28 = new ArrayList();
            Iterator var29 = var27.iterator();

            while(var29.hasNext()) {
                OnlCgreportItem var16 = (OnlCgreportItem)var29.next();

                var28.add(new OnlineFieldConfig(var16));
            }

            var15 = "rp_temp.";
            String var30 = DataBaseEnum.getDataBaseNameByValue(var9.getDbType());
            ConditionHandler var17 = new ConditionHandler(var15, var30);
            var17.setDaoType("jdbcTemplate");
            String var18 = var17.mo1320a(var28, params);
            Map var19 = var17.getSqlParams();
            String var20 = "select * from (" + sql + ") rp_temp ";
            if (var18.trim().length() > 0) {
                var20 = var20 + " where " + var18;
            }

            String var21 = CgReportSqlUtil.formatSqlStr(var20);
            Object var22 = params.get("column");
            if (var22 != null) {
                var20 = var20 + " order by rp_temp." + var22.toString() + " " + params.get("order").toString();
            }

            HashMap var23 = new HashMap();
            Map var24 = DynamicDBUtil.queryCount(dbKey, var21, var19);
            var23.put("total", var24.get("total"));
            List var25 = CgReportSqlUtil.m348a(String.valueOf(params.get("getAll")), dbKey, var20, var7, var8, var19);

            var23.put("records", CgformUtil.m280d(var25));
            return var23;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> editAll(OnlCgreportModel values) {
        OnlCgreportHead var2 = values.getHead();
        OnlCgreportHead var3 = (OnlCgreportHead)super.getById(var2.getId());
        if (var3 == null) {
            return Result.error("未找到对应实体");
        } else {
            super.updateById(var2);
            LambdaQueryWrapper<OnlCgreportItem> var4 = new LambdaQueryWrapper();
            var4.eq(OnlCgreportItem::getCgrheadId, var2.getId());
            this.onlCgreportItemService.remove(var4);
            LambdaQueryWrapper<OnlCgreportParam> var5 = new LambdaQueryWrapper();
            var5.eq(OnlCgreportParam::getCgrheadId, var2.getId());
            this.onlCgreportParamService.remove(var5);
            Iterator var6 = values.getParams().iterator();

            while(var6.hasNext()) {
                OnlCgreportParam var7 = (OnlCgreportParam)var6.next();
                var7.setCgrheadId(var2.getId());
            }

            var6 = values.getItems().iterator();

            while(var6.hasNext()) {
                OnlCgreportItem var8 = (OnlCgreportItem)var6.next();
                var8.setFieldName(var8.getFieldName().trim().toLowerCase());
                var8.setCgrheadId(var2.getId());
            }

            this.onlCgreportItemService.saveBatch(values.getItems());
            this.onlCgreportParamService.saveBatch(values.getParams());
            return Result.ok("全部修改成功");
        }
    }

    @Override
    @org.springframework.transaction.annotation.Transactional(rollbackFor = {java.lang.Exception.class})
    public Result<?> delete(java.lang.String id) {
        boolean var2 = super.removeById(id);
        if (var2) {
            LambdaQueryWrapper<OnlCgreportItem> var3 = new LambdaQueryWrapper();
            var3.eq(OnlCgreportItem::getCgrheadId, id);
            this.onlCgreportItemService.remove(var3);
            LambdaQueryWrapper<OnlCgreportParam> var4 = new LambdaQueryWrapper();
            var4.eq(OnlCgreportParam::getCgrheadId, id);
            this.onlCgreportParamService.remove(var4);
        }

        return Result.ok("删除成功");
    }


@Override
    @org.springframework.transaction.annotation.Transactional(rollbackFor = {java.lang.Exception.class})
public Result<?> bathDelete(java.lang.String[] ids) {
        String[] var2 = ids;
        int var3 = ids.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            String var5 = var2[var4];
            boolean var6 = super.removeById(var5);
            if (var6) {
                LambdaQueryWrapper<OnlCgreportItem> var7 = new LambdaQueryWrapper();
                var7.eq(OnlCgreportItem::getCgrheadId, var5);
                this.onlCgreportItemService.remove(var7);
                LambdaQueryWrapper<OnlCgreportParam> var8 = new LambdaQueryWrapper();
                var8.eq(OnlCgreportParam::getCgrheadId, var5);
                this.onlCgreportParamService.remove(var8);
            }
        }

        return Result.ok("删除成功");
    }

    @Override
    public List<String> getSqlFields(String sql, String dbKey) throws SQLException, DBException {
        if (StringUtils.isNotBlank(dbKey)) {
            return getListBySqlFields(sql, dbKey);
        }
        return getListBySqlFields(sql, null);
    }

    @Override
    public List<String> getSqlParams(String sql) {
        if (ConvertUtils.isEmpty(sql)) {
            return null;
        }
        ArrayList arrayList = new ArrayList();
        Matcher matcher = Pattern.compile("\\$\\{\\w+\\}").matcher(sql);
        while (matcher.find()) {
            String group = matcher.group();
            arrayList.add(group.substring(group.indexOf("{") + 1, group.indexOf("}")));
        }
        return arrayList;
    }

    private List<String> getListBySqlFields(String str, String str2) throws SQLException, DBException {
        Set<String> keySet;
        Set<String> set;
        if (ConvertUtils.isEmpty(str)) {
            return null;
        }
        String trim = str.replace("[^><]=", CgReportConstant.f374u).trim();
        if (trim.endsWith(";")) {
            trim = trim.substring(0, trim.length() - 1);
        }
        String sql = CgReportSqlUtil.replaceParamsForSQL(QueryGenerator.convertSystemVariables(trim));
        if (StringUtils.isNotBlank(str2)) {
            DynamicDataSourceModel cacheDynamicDataSourceModel = DataSourceCachePool.getCacheDynamicDataSourceModel(str2);
            if (!ReUtil.contains(" order\\s+by ", sql.toLowerCase()) || !"3".equalsIgnoreCase(cacheDynamicDataSourceModel.getDbType())) {
                Map<String, Object> a2 = CgReportSqlUtil.getSqlFiledForStrs(str2, sql);
                if (a2 == null) {
                    if (!sql.contains("*")) {
                        try {
                            a2 = CgReportSqlFiledParseUtils.getSqlFiledForStr(sql);
                        } catch (Exception e) {
                        }
                    }
                    if (a2 == null) {
                        throw new BootException("该报表sql没有数据");
                    }
                }
                keySet = a2.keySet();
            } else {
                throw new BootException("SqlServer不支持SQL内排序!");
            }
        } else {
            String databaseType = DbTableUtil.getDatabaseType();
            if (!ReUtil.contains(" order\\s+by ", sql.toLowerCase()) || !"SQLSERVER".equalsIgnoreCase(databaseType)) {
                log.info("--sql:{}",sql);
                List records = this.mapper.selectPageBySql(new Page<>(1, 1), sql).getRecords();
                if (records.size() < 1) {
                    if (!sql.contains("*")) {
                        try {
                            set = CgReportSqlFiledParseUtils.getSqlFiledForStr(sql).keySet();
                        } catch (Exception e2) {
                            set = null;
                        }
                    } else {
                        set = null;
                    }
                    if (set == null) {
                        throw new BootException("该报表sql没有数据");
                    }
                    keySet = set;
                } else {
                    keySet = ((Map) records.get(0)).keySet();
                }
            } else {
                throw new BootException("SqlServer不支持SQL内排序!");
            }
        }
        if (keySet != null) {
            keySet.remove("ROW_ID");
        }
        return new ArrayList(keySet);
    }

    @Override
    public Map<String, Object> queryCgReportConfig(String reportId) {
        HashMap hashMap = new HashMap(0);
        Map<String, Object> queryCgReportMainConfig = this.mapper.queryCgReportMainConfig(reportId);
        List<Map<String, Object>> queryCgReportItems = this.mapper.queryCgReportItems(reportId);
        List<OnlCgreportParam> queryCgReportParams = this.mapper.queryCgReportParams(reportId);
        if (DbTableUtil.m435a()) {
            hashMap.put(CgReportConstant.f354a, CgformUtil.m242a(queryCgReportMainConfig));
            hashMap.put(CgReportConstant.f355b, CgformUtil.m280d(queryCgReportItems));
        } else {
            hashMap.put(CgReportConstant.f354a, queryCgReportMainConfig);
            hashMap.put(CgReportConstant.f355b, queryCgReportItems);
        }
        hashMap.put(CgReportConstant.f356c, queryCgReportParams);
        return hashMap;
    }

    @Override
    @Deprecated
    public List<DictModel> queryDictSelectData(String sql, String keyword) {
        ArrayList arrayList = new ArrayList();
        Page<Map<String, Object>> page = new Page<>();
        page.setSearchCount(false);
        page.setCurrent(1);
        page.setSize(10);
        String sql2 = sql.trim();
        int lastIndexOf = sql2.lastIndexOf(";");
        if (lastIndexOf == sql2.length() - 1) {
            sql2 = sql2.substring(0, lastIndexOf);
        }
        if (keyword != null && !"".equals(keyword)) {
            String str = " like '%" + keyword + "%'";
            sql2 = "select * from (" + sql2 + ") t where t.value " + str + " or " + "t.text" + str;
        }
        List records = this.baseMapper.selectPageBySql(page, sql2).getRecords();
        if (records == null || records.size() == 0) {
            return arrayList;
        }
        return JSON.parseArray(JSON.toJSONString(records), DictModel.class);
    }

    @Override
    @Cacheable(key = "'column-'+#code+'-'+#queryDict", value = {"sys:cache:online:rp"})
    public Map<String, Object> queryColumnInfo(String code, boolean queryDict) {
        HashMap hashMap = new HashMap();
        QueryWrapper queryWrapper = new QueryWrapper();
        ((QueryWrapper) ((QueryWrapper) queryWrapper.eq("cgrhead_id", code)).eq("is_show", 1)).orderByAsc("order_num");
        List<OnlCgreportItem> list = this.onlCgreportItemService.list(queryWrapper);
        JSONArray jSONArray = new JSONArray();
        JSONArray jSONArray2 = new JSONArray();
        HashMap hashMap2 = new HashMap();
        boolean z = false;
        for (OnlCgreportItem onlCgreportItem : list) {
            JSONObject jSONObject = new JSONObject(4);
            jSONObject.put("title", onlCgreportItem.getFieldTxt());
            jSONObject.put("dataIndex", onlCgreportItem.getFieldName());
            jSONObject.put("fieldType", onlCgreportItem.getFieldType());
            jSONObject.put("align", CgformUtil.f256aC);
            jSONObject.put("sorter", "true");
            jSONObject.put("isTotal", onlCgreportItem.getIsTotal());
            jSONObject.put("groupTitle", onlCgreportItem.getGroupTitle());
            if (ConvertUtils.isNotEmpty(onlCgreportItem.getGroupTitle())) {
                z = true;
            }
            String fieldType = onlCgreportItem.getFieldType();
            if ("Integer".equals(fieldType) || "Date".equals(fieldType) || "Long".equals(fieldType)) {
                jSONObject.put("sorter", "true");
            }
            if (StringUtils.isNotBlank(onlCgreportItem.getFieldHref())) {
                String str = OnlSlotRender.f326e + onlCgreportItem.getFieldName();
                JSONObject jSONObject2 = new JSONObject();
                jSONObject2.put("customRender", str);
                jSONObject.put("scopedSlots", jSONObject2);
                JSONObject jSONObject3 = new JSONObject();
                jSONObject3.put("slotName", str);
                jSONObject3.put("href", onlCgreportItem.getFieldHref());
                jSONArray.add(jSONObject3);
            }
            String dictCode = onlCgreportItem.getDictCode();
            if (dictCode != null && !"".equals(dictCode)) {
                if (queryDict) {
                    hashMap2.put(onlCgreportItem.getFieldName(), queryColumnDict(onlCgreportItem.getDictCode(), null, null));
                    jSONObject.put("customRender", onlCgreportItem.getFieldName());
                } else {
                    jSONObject.put("dictCode", dictCode);
                }
            }
            jSONArray2.add(jSONObject);
        }
        if (queryDict) {
            hashMap.put("dictOptions", hashMap2);
        }
        hashMap.put("columns", jSONArray2);
        hashMap.put("fieldHrefSlots", jSONArray);
        hashMap.put("isGroupTitle", Boolean.valueOf(z));
        return hashMap;
    }

    @Override
    public List<DictModel> queryColumnDict(String dictCode, JSONArray records, String fieldName) {
        if (ConvertUtils.isNotEmpty(dictCode)) {
            if (dictCode.trim().toLowerCase().indexOf("select ") != 0 || (fieldName != null && records.size() <= 0)) {
                return this.sysBaseAPI.queryDictItemsByCode(dictCode);
            }
            String dictCode2 = dictCode.trim();
            int lastIndexOf = dictCode2.lastIndexOf(";");
            if (lastIndexOf == dictCode2.length() - 1) {
                dictCode2 = dictCode2.substring(0, lastIndexOf);
            }
            String str = "SELECT * FROM (" + dictCode2 + ") temp ";
            if (records != null) {
                ArrayList arrayList = new ArrayList();
                for (int i = 0; i < records.size(); i++) {
                    String string = records.getJSONObject(i).getString(fieldName);
                    if (StringUtils.isNotBlank(string)) {
                        arrayList.add(string);
                    }
                }
                str = str + "WHERE temp.value IN (" + (CgformUtil.f229C + StringUtils.join(arrayList, "','") + CgformUtil.f229C) + ")";
            }
            List<Map<?, ?>> executeSelete = getBaseMapper().executeSelete(str);
            if (!(executeSelete == null || executeSelete.size() == 0)) {
                return JSON.parseArray(JSON.toJSONString(executeSelete), DictModel.class);
            }
        }
        return null;
    }
}
